package com.exam.api.config.validation.validator;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;


public class InArrayValidator implements ConstraintValidator<InArray, Object> {

    private InArray inArray;

    @Override
    public void initialize(InArray inArray) {
        this.inArray = inArray;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null){
            return true;
        }
        String valueStr = StrUtil.toString(value);
        if (StrUtil.isEmpty(valueStr)) {
            return true;
        }
        if (StrUtil.equalsAny(valueStr, inArray.value())) {
            return true;
        }
        HibernateConstraintValidatorContext hibernateContext = constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class);
        hibernateContext.addMessageParameter("value", StrUtil.join(StrUtil.COMMA, CollUtil.toList(inArray.value())));
        hibernateContext.addMessageParameter("oValue", value);
        hibernateContext.buildConstraintViolationWithTemplate("该值不支持 {oValue}， 仅支持 {value}").addConstraintViolation();
        return false;
    }
}
